package Servlet.member;

import domain.News;
import service.NewsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/news")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置参数，默认为1
        Long newsTypeId = 1L;
        Long pageIndex = 0L;
        Long pageSize = 3L;
        String reqTypeId=request.getParameter("reqNewsTypeId");
        String reqPageIndex=request.getParameter("reqPageIndex");


        // 当id值不为空时，将字符串id转换为Long数字类型
        if (reqTypeId != null) {
            newsTypeId = Long.parseLong(reqTypeId);
        }
        if (reqPageIndex != null){
            pageIndex = (Long.parseLong(reqPageIndex) - 1) * pageSize;
        }

        // 获取从数据库查询出来的集合
        List<News> newsList = NewsService.getNewsByTypeId(newsTypeId,pageIndex,pageSize);
        int total = NewsService.getNewsTotalByTypeId(newsTypeId);
        Long pageCount = total / pageSize;

        if (total % pageSize != 0) pageCount++;


//        System.out.println(pageCount);
        // 将newsList集合储存到域对象中
        request.setAttribute("newsList", newsList);
        request.setAttribute("total", total);
        request.setAttribute("pageCount", pageCount);
        request.setAttribute("newsTypeId", newsTypeId);
        request.setAttribute("reqPageIndex", reqPageIndex);

        // 跳转到‘/index.jsp’页面
        request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
